import React, { useEffect, useReducer } from 'react';

const useForm = initalFields => {
  const formReducer = (state, action) => {
    console.log('reducer 执行', action);
    const { type, values } = action;
    switch (type) {
      case 'set': {
        return {
          ...state,
          ...values,
        };
      }
      case 'reset': {
        return initalFields;
      }
      default:
        break;
    }

    return state;
  };
  const [values, dispatch] = useReducer(formReducer, initalFields);

  const getFieldsProps = key => {
    // 给 input 做属性用
    return {
      value: values[key], // values[key] ? values.user
      onChange: event =>
        dispatch({ type: 'set', values: { [key]: event.target.value } }),
    };
  };

  const setFieldsValue = values => {
    dispatch({ type: 'set', values });
  };

  const resetFields = () => {
    dispatch({ type: 'reset' });
  };

  return { values, getFieldsProps, setFieldsValue, resetFields };
};

function Input() {
  const { getFieldsProps, setFieldsValue,resetFields } = useForm({
    user: '',
    pswd: '',
  });

  return (
    <div>
      <input placeholder="用户名" {...getFieldsProps('user')} />
      <input type="password" placeholder="密码" {...getFieldsProps('pswd')} />
      <button
        onClick={() => setFieldsValue({ pswd: '88888888', user: 'Millet' })}
      >
        设置密码
      </button>
      <button onClick={resetFields}>重置</button>
      <button>提交</button>
    </div>
  );
}

export default Input;
